package com.mjf.net.upload;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 文件上传服务端
 *
 * 查看端口情况：netstat -anb | more
 */
public class TCPFileUploadServer {
    public static void main(String[] args) throws Exception {

        ServerSocket ss = new ServerSocket(8888);
        System.out.println("服务端开始监听8888端口");

        // 等待客户端连接
        Socket socket = ss.accept();

        // 通过 Socket 读取数据
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        byte[] bytes = StreamUtils.streamToByteArray(bis);  // 文件对应的字节数组
        socket.shutdownInput(); // 关闭 Socket 输入流

        String filePath = "D:\\coding\\idea\\java-stu\\output\\tcp_file_copy.png";
        // 将文件写入磁盘
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
        bos.write(bytes);
        bos.close();

        // 文件收到以后向客户端发送正确回执
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bw.write("success");
        bw.flush();
        socket.shutdownOutput();    // 关闭 Socket 输出流

        bis.close();
        bw.close();
        socket.close();
        ss.close();

    }
}
